package com.gxa.medical.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        // 跨域
        String origin = httpServletRequest.getHeader("Origin");
        if (origin == null) {
            httpServletResponse.addHeader("Access-Control-Allow-Origin","*");
        } else {
            if (httpServletRequest.getMethod().equals("OPTIONS")) {
                httpServletResponse.addHeader("Access-Control-AllowOrigin", origin);
            }
            httpServletResponse.addHeader("Access-Control-Allow-Origin",
                    origin);
        }
        httpServletResponse.addHeader("Access-Control-Allow-Headers","Origin, x-requested-with, Content-Type, Accept,XCookie");
        httpServletResponse.addHeader("Access-Control-AllowCredentials", "true");
        httpServletResponse.addHeader("Access-Control-Allow-Methods","GET,POST,PUT,OPTIONS,DELETE");
        if (httpServletRequest.getMethod().equals("OPTIONS")) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    @Override
    public void destroy() {
    }
}
